package com.yaosheng.thread.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * Created by yaosheng on 2021/7/1.
 */
public class Test06 {

    volatile List lists = new ArrayList ();

    static Thread t1 = null,t2 = null;

    public void add(Object o){
        lists.add (o);
    }

    public int size(){
        return lists.size ();
    }

    public static void main(String[] args) {

        Test06 test06 = new Test06 ();
        Semaphore s = new Semaphore (1);

        t1 = new Thread ( () -> {

            try {
                s.acquire ();
                for(int i = 0;i < 5;i ++) {
                    test06.add (new Object ());
                    System.out.println ("add" + i);
                }
                s.release ();
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }

            try {
                t2.start ();
                t2.join ();
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }

            try {
                s.acquire ();
                for(int i = 0;i < 10;i ++) {
                    System.out.println (i);
                }
                s.release ();
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
        },"t1");

        t2 = new Thread ( () -> {

            try {
                s.acquire ();
                System.out.println ("t2启动");
                s.release ();
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }

            try {
                s.acquire ();
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
        },"t2");

        t1.start ();
        //t2.start ();
    }
}
